package com.superquan.selfstudybootmybatis.utils.encrypt.md5;

import com.google.gson.Gson;
import com.superquan.selfstudybootmybatis.entity.common.NczBaseResult;
import com.superquan.selfstudybootmybatis.utils.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.DigestUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @Auther: wanggang(323492)
 * @Date: 2021/6/25 20:31
 * @Description:
 */
public class NopApiTest {

    private final static char[] LowHex = "0123456789abcdef".toCharArray();

    private final static String TARGET_URL = "https://opensandbox.ncarzone.com/api/scfservice/queryServiceOrderByVerifyBatch";

    private final static String TEST_APP_SECRET = "ab3cae7eb827c56d199c69e2d48273853725bbeb";
    private final static String TEST_APP_KEY = "2022081711201";

    public static void main(String[] args) {
        NczBaseResult result = new NczBaseResult();
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        Map<String, String> params = new HashMap<>(8);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        params.put("app_key", TEST_APP_KEY);
        String dateTime = String.valueOf(System.currentTimeMillis());
//        params.put("appName", "tmallcar");
//        params.put("version", "8.6.5");
        params.put("verifyCode", "9279418402721");
        params.put("nczStoreId", "307322905");
        params.put("timestamp", dateTime);
        params.put("sign", generateSign(TEST_APP_SECRET, params));

        MultiValueMap<String, String> map = new LinkedMultiValueMap();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            map.add(entry.getKey(), entry.getValue());
        }
        // 组装请求体
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        String str = restTemplate.postForObject(TARGET_URL, request, String.class);
        result = JsonUtil.parseJSONObject(str, NczBaseResult.class);
        System.out.println(JsonUtil.toJSONString(result));
    }

    /**
     * @param appSecret
     * @param requestParams
     * @return
     */
    private static String generateSign(String appSecret, Map<String, String> requestParams) {
        String[] keys = requestParams.keySet().toArray(new String[0]);
        Arrays.sort(keys);
        StringBuffer query = new StringBuffer();
        query.append(appSecret);
        for (String key : keys) {
            if (StringUtils.isNotEmpty(requestParams.get(key))) {
                query.append(key).append(requestParams.get(key));
            }
        }
        query.append(appSecret);
        return DigestUtils.md5DigestAsHex(query.toString().getBytes());
    }

    /**
     * 结果和DigestUtils.md5DigestAsHex()一致
     *
     * @param originStr
     * @return
     */
    @Deprecated
    private static String md5EncryptLowerCase(final String originStr) {
        byte[] bytes = null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            bytes = messageDigest.digest((originStr).getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            //log.warn(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            //log.warn(e.getMessage(), e);
        }
        StringBuilder s = new StringBuilder();
        for (int i = 0; bytes != null && i < bytes.length; i++) {
            s.append(LowHex[(bytes[i] >>> 4) & 0xf]);
            s.append(LowHex[bytes[i] & 0xf]);
        }
        return s.toString();
    }
}
